
import { App, Component, ComponentInternalInstance, ComponentPublicInstance, createApp, watch,ref, VNode, VNodeChild } from "vue"
import {message} from "./message" 
import messageDom from "./message.vue"

interface Option{
    message?:string,
    type?:string,
    duration?:number,
    icon?:string
}

const MessageArr = ref<any>([])

let obj = ["success","warning","info","error"] as const


export const Message:any= function(options:Option){
    // console.log(options,"options")

    let vnode = createApp(messageDom,{...options})
    showMessage(vnode,options.duration!)
    
    
    
}

// 显示消息
const showMessage = (app:App,duration:number)=>{
    const oFrag = document.createDocumentFragment()
    let vm:Component = app.mount(oFrag)
    //每次显示的时候都要加进去记录一下
    MessageArr.value.push(vm)

    document.body.appendChild(oFrag)
    setTopfn(vm)
    vm.traggerVisible(true) 
    // console.log(app,"app")
    watch(MessageArr,()=>setTopfn(vm))
    hideMessage(app,vm,duration)
}

// 隐藏消息 
 const hideMessage = (app:App,vm:any,duration:number)=>{
  vm.timer=  setTimeout( async() => {
        await vm.traggerVisible(false)
        app.unmount();
        MessageArr.value = MessageArr.value.filter((item:typeof vm)=>item!=vm)
        clearTimeout(vm.timer)
        vm.timer = null
    }, duration || 3000);
 }

// 根据vm多少个设置top高度

const setTopfn = (vm:any)=>{
    const {setTop,height,margin} =vm
    const currentIndex = MessageArr.value.findIndex((item:typeof vm)=>item===vm )
    setTop(margin * (currentIndex+1)+height*currentIndex)
    // console.log(currentIndex,"currentIndex")
}

obj.forEach(type=>{  
   Message[type] = (options:Option)=>{
        options.type = type
       return Message(options)
   }
})